<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * 用户_控制器
 * 	进入该控制器需用户已登录
 * @property User_mdl $users
 * @property UserORM  $user
 */
class User extends MY_Controller {

	const E_BAD_PHONE = - 2;//手机号码格式不正确
	const E_BAD_CAPTCHA = -3;//短信验证码不正确
	const E_PWD_EVER_SET = -211;//已经设置过密码
	const E_PWD_OLD_BAD = -212;//旧密码不正确
	const E_PWD_FORMAT_BAD = -213;// 密码格式不正确(少于6位)
	const E_CAN_COMBINE = -4;// 可以合并
	const E_CANNOT_COMBINE = -5;// 不可以合并
	const E_BOUND_PHONE = -222;//已经绑定过手机
	const E_BOUND_WX = -223;//已绑定过微信
	const E_USER_NOT_FOUND = -230;//没找到用户


	public function __construct(){
		parent::__construct();
		$this->load->model('User_mdl','users');
		$this->user = parent::getLoginUser();
	}
	/**
	 * API:用户基本信息
	 */
	public function index(){
		debug('currentPhoneID',$this->user->currentPhoneID);
		$this->apiOutput->put('user', $this->user->getBaseInfo())->out();
	}



	/**
	 * API:绑定手机
	 */
	public function bind_phone(){
		$input = check_input($_REQUEST,array('phone','captcha'));
		if( !$input ){
			$this->apiOutput->errorInput();
		}
		if( empty($input['phone']) ){
			$this->apiOutput->error('手机号码格式不正确',self::E_BAD_PHONE);
		}
		$this->load->library('PhoneCaptcha',NULL,'captcha');
		if( !$this->captcha->check($input['phone'],$input['captcha']) ){
			$this->apiOutput->error('验证码错误',self::E_BAD_CAPTCHA);
		}

		if( !empty($this->user->phone) ){
		    $this->apiOutput->error('您已经绑定过手机,不允许修改',self::E_BOUND_PHONE);
		}

		// 查找要绑定的手机是否已注册
		$where = array('phone'=>$input['phone']);
		$pUser  = $this->users->findOne($where);
		if( !empty($pUser) ){
			if (! empty ( $pUser->wxOpenID )) {
				$this->apiOutput->put ( 'nickname', $pUser->nickname )
								->error ( '您要绑定的手机已经绑定了其他微信,请更换手机!', self::E_CANNOT_COMBINE );
			}
			$this->apiOutput->put ( 'user', $pUser->getBaseInfo () )
							->error ( '该手机已注册,是否绑定?', self::E_CAN_COMBINE );
		}

		$this->user->phone = $input['phone'];

		if( $this->user->update() ){
		    $this->apiOutput->put('msg', '绑定手机成功')->out();
		}else{
		    $this->apiOutput->errorSystem();
		}
	}
	/**
	 * 绑定微信
	 */
	public function bind_wechat(){
		$input = check_input ( $_REQUEST, array (
				'wxOpenID',//微信openID
				'nickname',//微信昵称
				'headImgUrl',//微信头像URL
				'wxUnionID',//微信unionID
		) );
		if( !$input ){
		    $this->apiOutput->errorInput();
		}

		$weChat = $this->user->wxOpenID;
		if( !empty($weChat) ){
		    $this->apiOutput->error('您已经绑定过微信,不允许修改',self::E_BOUND_WX);
		}

		$where = array('wxOpenID'=>$input['wxOpenID']);
		$wxUser = $this->users->findOne($where);
		if( !empty($wxUser) ){
			if( ! empty($wxUser->phone) ){
				$msg = "绑定失败:您要绑定的微信已经跟[{$wxUser->phone}]绑定";
				$this->apiOutput->put('nickname', $wxUser->nickname)
					->error($msg,self::E_CANNOT_COMBINE);
			}
			$this->apiOutput->put('user',$wxUser->getBaseInfo())
							->error('该微信已注册,是否绑定?',self::E_CAN_COMBINE);
		}
		$this->user->wxOpenID    = $input['wxOpenID'];
		$this->user->nickname    = $input['nickname'];
		$this->user->headImgUrl  = $input['headImgUrl'];
		$this->user->wxOpenID    = $input['wxOpenID'];
		$this->user->wxUnionID   = $input['wxUnionID'];

		if( $this->user->update() ){
		    $this->apiOutput->put('msg', '绑定微信成功')->out();
		}else{
		    $this->apiOutput->errorSystem();
		}

	}

	public function combine(){
		$userID = (int)$this->input->post_get('userID');
		$type   = (int)$this->input->post_get('type');

		$otherUser = $this->users->findOneByID($userID);
		if( empty($otherUser) ){
			$this->apiOutput->error('无该用户',self::E_USER_NOT_FOUND);
		}
		switch ($type) {
			case 1:// 手机用户合并微信用户
				$pUser = &$this->user;
				$wxUser = &$otherUser;
				if ( !empty($pUser->wxOpenID) ) {
					$this->apiOutput->error('你已绑定过微信,不能合并其他微信账户',-203);
				}

				if ( !empty($wxUser->phone) ) {
					$this->apiOutput->error('你要合并的微信账户已绑定其他手机,不能进行合并',-204);
				}
				break;
			case 2:// 微信用户合并手机用户
				$wxUser = &$this->user;
				$pUser  = &$otherUser;
				if( ! empty($wxUser->phone) ){
					$this->apiOutput->error('你已绑定过手机,不能合并其他手机账户',-205);
				}

				if( ! empty($pUser->wxOpenID) ){
					$this->apiOutput->error('你要合并的手机账户已绑定其他微信,不能进行合并',-206);
				}
				break;
			default:
				$this->apiOutput->errorInput();
				break;
		}
		if( empty($pUser->phone) ){
			$this->apiOutput->error('你未绑定手机',-201);
		}
		if( empty($wxUser->wxOpenID) ){
			$this->apiOutput->error('你未绑定微信',-202);
		}
		// ==== 选择保留的主账户 =====
		// 如果微信账户的 余额,累计充值,累计消费,累计赠送 等纪录有一项不为空
		// 则选择微信账户为主账户
		// 否则选择手机账户为主账户
		$moneyKeys = array (
				'balance',
				'rechargeTotal',
				'buyTotal',
				'presrent'
		);
		$mainUser = $pUser;
		$delUser  = $wxUser;
		foreach ( $moneyKeys as $key ) {
			if ($wxUser->{$key} != 0) {
				$mainUser = $wxUser;
				$delUser = $pUser;
				break;
			}
		}
		$user = $this->users->combine($mainUser, $delUser);
		if (empty($user)) {
			$this->apiOutput->errorSystem();
		}
		$user->afterLogin( $this->user->currentPhoneID );
		$this->apiOutput->put('user',$user->getBaseInfo())->out();
	}

	/**
	 * 修改密码
	 */
	public function change_pwd(){
		$oldPwd = $this->input->post_get('oldpwd');
		$newPwd = $this->input->post_get('newpwd');
		if( strlen($newPwd) < 6 ){
			$this->apiOutput->error('密码不得少于6位',self::E_PWD_FORMAT_BAD);
		}
		if( ! $this->user->checkPassword($oldPwd) ){
			$this->apiOutput->error('旧密码不正确!',self::E_PWD_OLD_BAD);
		}
		if( $this->user->setPassword($newPwd,TRUE) ){
			$this->apiOutput->put('msg', '密码设置成功!')->out();
		}else{
			$this->apiOutput->errorSystem();
		}
	}
	/**
	 * 设置密码:必须未设置过密码
	 */
	public function set_pwd(){
		$pwd = $this->input->post_get('pwd');
		if( ! empty($this->user->password) ){
			$this->apiOutput->error('您已设置过密码!请通过修改密码或者忘记密码重置密码!',self::E_PWD_EVER_SET);
		}

		if( strlen($pwd) < 6 ){
			$this->apiOutput->error('密码不得少于6位',self::E_PWD_FORMAT_BAD);
		}

		if( $this->user->setPassword($pwd,TRUE) ){
			$this->apiOutput->put('msg', '密码设置成功!')->out();
		}else{
			$this->apiOutput->errorSystem();
		}
	}

	public function set_school(){
		$schoolID = (int)$this->input->post_get('schoolID');
		if( $schoolID <= 0 ){
			$this->apiOutput->errorInput();
		}

		$this->user->schoolID = $schoolID;
		if( ! $this->user->update() ){
			$this->apiOutput->errorSystem();
		}

		$this->apiOutput->put('msg', '学校设置成功!')->out();
	}

	/**
	 * 更新基本资料
	 */
	public function update(){

		$input = check_input($_REQUEST);
		foreach ($input as $field => $val) {
			if( $val==='' ){
				continue;
			}
			switch ($field) {
				// ----昵称----
				case 'nickname':
					if( strLength($val) > 12 ){
						$this->apiOutput->error('用户昵称不得超过12个字符',-21);
					}
					if( empty($val) ){
						$this->apiOutput->error('用户昵称不得为空',-21);
					}
					$this->user->nickname = $val;
					break;
			}
		}

		if( $this->user->update() ){
			$this->apiOutput->put('user', $this->user->getBaseInfo());
		}else{
			$this->apiOutput->errorSystem();
		}

	}
	/**
	 * 上传头像
	 */
	public function upload_headimg(){

		$dir = 'upload/userHeadImg/';
		$file = $this->user->id.'_'.time();
		$config = array(
				'upload_path'=>FCPATH.$dir,
				'allowed_types'=>'gif|jpg|png|jpeg',
				'max_size'=>1024,
				'file_name'=>$file,
		);

		if( ! is_dir($config['upload_path']) ){
			mkdir($config['upload_path']);
		}

		$this->load->library('upload',$config);
		if( ! $this->upload->do_upload('imgFile') ){
			// 上传失败:
			$msg = strip_tags( $this->upload->display_errors() );
			debug('upload_error',$msg);
			$this->apiOutput->error('头像上传失败:'.$msg,-41);
		}else{
			// 上传成功
			$data = $this->upload->data();
			$host = 'http://'.$_SERVER['SERVER_NAME'];
			$url = $dir.$data['orig_name'];
			// 更新到数据库
			$oldPortrait = $this->user->headImgUrl;
			$this->user->headImgUrl = $url;
			if( $this->user->update() ){
				// 更新成功:删除旧头像的本地图片
				if( ! empty($oldPortrait) ){
					$info = parse_url($oldPortrait);
					$filepath = FCPATH.$info['path'];
					if( file_exists($filepath) ){
						unlink($filepath);
					}
				}
				// 输出信息
				$out['msg'] = '上传头像成功';
				$out['url'] = base_url($url);
				$this->apiOutput->out($out);
			}else{// 更新到数据库失败:
				$this->apiOutput->errorSystem();
			}
		}
	}

	public function logout(){
		$res = $this->user->logout();
		$this->apiOutput->msg('退出成功!');
	}

    /**
     * 获取用户自动扣费状态
     * @return void
     */
    public function auto_charging(){
        $uid = $this->user->id;
        $model = new User_mdl();
        $result = $model->getOne(['id'=>$uid],'auto_charging,open_charging_time,close_charging_time');
        $open_time = $close_time = '';
        $status = $result['auto_charging'];
        if($result['open_charging_time']) $open_time = date('Y-m-d H:i:s',$result['open_charging_time']);
        if($result['close_charging_time']) $close_time = date('Y-m-d H:i:s',$result['close_charging_time']);
        $data = [
            'status'=>$status,
            'openTime'=>$open_time,
            'closeTime'=>$close_time
        ];
        $this->apiOutput->out($data);
    }
}
